//
//  xesAppSpeechAssessment.m
//  TestWeb
//
//  Created by tianlong on 2018/8/10.
//  Copyright © 2018年 tianlong. All rights reserved.
//

#import "xesAppSpeechAssessment.h"
//#import <LivePlayer/QuizAVPlayer.h>
//#import "ISEManager.h"

#define OCCallJS_SpeechIdentifier @"xesApp.speechAssessment"

@interface xesAppSpeechAssessment ()//<ISEManagerDelegate>
//@property (nonatomic, strong) QuizAVPlayer *player;
//@property (nonatomic, strong) ISEManager *iseManager;
@property (nonatomic,   copy) NSString *speechReusult;
@property (nonatomic, assign) NSInteger speechStatus;
@property (nonatomic,   copy) NSString *videoCatchPath;
@end

@implementation xesAppSpeechAssessment

- (instancetype)init
{
    self = [super init];
    if (self) {
//        self.player = [QuizAVPlayer sharedQuizAVPlayer];
        [self addAVPlayerObserver];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:)                                              name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    return self;
}

#pragma mark - 前台后台监听
- (void)appWillResignActive:(NSNotification *)note {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.webView stringByEvaluatingJavaScriptFromString:@"xesApp.speechAssessmentJs.appWillResignActive()"];
    });
}

- (void)appDidBecomeActive:(NSNotification *)note {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.webView stringByEvaluatingJavaScriptFromString:@"xesApp.speechAssessmentJs.appDidBecomeActive()"];
    });
}

#pragma mark - AVPlayer通知以及回调
- (void)addAVPlayerObserver{
    // 接收video初始化时设置通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quizVideInitData:) name:quizVedioInitData object:nil];
//    // 接受每秒发送的slider进度数据
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quizVedioSliderShowCurrentTime:) name:quizVedioSliderCurrentTime object:nil];
//    // 单条控制暂停状态
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quizVedioPlayFinishedMethod:) name:quizVedioPlayFinished object:nil];
//    // 播放准备失败
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quizAVPlayerStatusFailedMethod) name:quizAVPlayerStatusFailed object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerPause:) name:Quiz_AVPlayerPause object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerPlay:) name:Quiz_AVPlayerPlay object:nil];
}

- (void)removeNotificationCenterObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 准备播放
- (void)quizVideInitData:(NSNotification *)note{
    NSLog(@"%s",__FUNCTION__);
}

- (void)playerPlay:(NSNotification *)note {
    //开始播放回调
    [self callJSWithFuntion:@"xesApp.speechAssessmentJs.onPlayJs()"];
    NSLog(@"%s",__FUNCTION__);
}

- (void)quizVedioSliderShowCurrentTime:(NSNotification*)note{
    NSLog(@"%s",__FUNCTION__);
}

// 暂停播放
- (void)playerPause:(NSNotification*)note{
    [self callJSWithFuntion:@"xesApp.speechAssessmentJs.onPlayStopJs()"];
    NSLog(@"%s",__FUNCTION__);
}

// 播放完成的通知
- (void)quizVedioPlayFinishedMethod:(NSNotification *)note{
//    self.player.isPlaying = NO;
    NSLog(@"%s",__FUNCTION__);
}

// 播放失败
- (void)quizAVPlayerStatusFailedMethod{
    NSLog(@"%s",__FUNCTION__);
}

#pragma mark - JS Call OC

/** 播放语音 */
- (void)playVoice:(NSString *)url {
    
//    if ([self.delegate respondsToSelector:@selector(playVoice:)]) {
//        [self.delegate playVoice:url];
//    }
//
//    if(url){
//        if([url rangeOfString:@"http"].location != NSNotFound) {
//            [self.player playWithVideoUrl:[NSURL URLWithString:url] withVideoIndex:0];
//        }else {
//            [self.player playWithVideoUrl:[NSURL fileURLWithPath:url] withVideoIndex:0];
//        }
//        //[UMSAgentUtil postDebugId:WXJSDebugEventID label:@"js_call_oc_playVoice_Url" attachment:url];
//    }else {
//        //[UMSAgentUtil postDebugId:WXJSDebugEventID label:@"js_call_oc_playVoice_nullUrl" attachment:@""];
//    }
    NSLog(@"%s",__FUNCTION__);
}

/** 暂停播放接口 */
- (void)pauseVoice:(NSString *)url {
    
//    if ([self.delegate respondsToSelector:@selector(pauseVoice:)]) {
//        [self.delegate pauseVoice:url];
//    }
//    if(url){
//        [self.player pause];
//    }else {
//    }
    
    NSLog(@"%s",__FUNCTION__);
}

/** 停止播放接口 */
- (void)stopVoice:(NSString *)url {
//    NSURL *videoUrl = [NSURL fileURLWithPath:url];
//    if ([self.delegate respondsToSelector:@selector(stopVoice:)]) {
//        [self.delegate stopVoice:videoUrl.absoluteString];
//    }
//    if(url){
//        [self.player pause];
//        [self.webView stringByEvaluatingJavaScriptFromString:@"xesApp.speechAssessmentJs.onPlayStopJs()"];
//    }else {
//    }
    NSLog(@"%s",__FUNCTION__);
}

/** 手动暂停识别 */
- (void)stopTranslateVoice {
    if ([self.delegate respondsToSelector:@selector(stopTranslateVoice)]) {
        [self.delegate stopTranslateVoice];
    }
    //    [self.iseManager cancel];
//    [self.iseManager stopListening];
    NSLog(@"%s",__FUNCTION__);
}

/** 重新提交测评 */
- (void)reTranslateVoice {
    if ([self.delegate respondsToSelector:@selector(reTranslateVoice)]) {
        [self.delegate reTranslateVoice];
    }
    [self callJSWithFuntion:[NSString stringWithFormat:@"xesApp.speechAssessmentJs.onResultJs(%ld,%@)",self.speechStatus,self.speechReusult]];
    NSLog(@"%s",__FUNCTION__);
}

/**
 * 识别音频并返回识别结果接口
 * source         识别内容                    string
 * sourceType     识别内容类型(1英语，2中文)     int
 * isOnline       true在线，false离线          boolean
 * voiceName      录音文件名                   string
 * return         返回值：录制音频地址
 */
- (NSString *)translateVoice:(id)obj {
    
    NSArray *params = [JSContext currentArguments];
    
    if(params.count!=4) {
        NSLog(@"JS传递的参数有误");
        return @"";
    }
    
    if ([self.delegate respondsToSelector:@selector(translateVoice:)]) {
        [self.delegate translateVoice:obj];
    }
    
    NSString *source    = nil;
    int sourceType      = 0;
    BOOL isOnline       = NO;
    NSString *voiceName = nil;
    for(int i = 0; i < params.count; i++) {
        JSValue *value = [params objectAtIndex:i];
        if(i==0){
            source      = [value toString];
        }else if (i==1){
            sourceType  = [value toInt32];
        }else if (i==2){
            isOnline    = [value toBool];
        }else if (i==3){
            voiceName   = [value toString];
        }
    }
    
//    if(!self.iseManager){
//        self.iseManager = [[ISEManager alloc]initWithDelegate:self engineType:sourceType==1?ISEManagerAppTypeLiveEnglish:ISEManagerAppTypeChineseEvaluation];
//    }
//
//    if(isOnline){
//        [self.iseManager startOnlineListeningSentence:source];
//    }else {
//        [self.iseManager startListeningSentence:source];
//    }
    
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString * tempPath = [NSString stringWithFormat:@"%@/voiceDefault.mp3",cachePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isFile = [fileManager fileExistsAtPath:tempPath];
    if(isFile) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss.SSS"];
        NSString *timeSp        = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
        NSString *fileName      = [NSString stringWithFormat:@"%@_%@.mp3",timeSp,voiceName];
        NSString *videoTempPath = [cachePath stringByAppendingPathComponent:@"jsVideo"];
        NSString *videCachePath = [videoTempPath stringByAppendingString:fileName];
        BOOL success = [fileManager copyItemAtPath:tempPath toPath:videCachePath error:nil];
        if (success) {
            self.videoCatchPath = videCachePath;
            NSLog(@"%s_recordAddress=%@",__FUNCTION__,self.videoCatchPath);
        }
    }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"模拟两秒后调用_onISEResultInRecognizing");
        [self onBeginOfSpeech];
        [self onVolumeChanged:100];
        [self onISEResultInRecognizing:@(10) withCode:10];
    });
    
    return self.videoCatchPath;
}

#pragma mark - ISEManagerDelegate
/** 开始录音回调 */
- (void)onBeginOfSpeech {
    [self callJSWithFuntion:@"xesApp.speechAssessmentJs.onBeginOfSpeechJs()"];
    NSLog(@"%s",__FUNCTION__);
}

/** 音量和数据回调 */
- (void)onVolumeChanged:(int)volume {
    [self callJSWithFuntion:[NSString stringWithFormat:@"xesApp.speechAssessmentJs.onVolumeUpdateJs(%d)",100]];
    NSLog(@"%s_volume=%d",__FUNCTION__,volume);
}

/** 录音数据回调 */
-(void)onReceivedPcmDataOfSpeech:(NSData *)pcmData {
    //    NSLog(@"%s",__FUNCTION__);
}

/** 停止录音回调 */
- (void)onEndOfSpeech {
    NSLog(@"%s",__FUNCTION__);
}

/** 测评中的返回结果 */
-(void)onISEResultInRecognizing:(id)result withCode:(NSInteger)codeNo {
    [self callJSResult:result];
}

/** 解析结果回调 */
-(void)onISEResultXmlParserResult:(id)result {
    
}

- (void)callJSResult:(id)result {
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"xesApp.speechAssessmentJs.onResultJs(%d,%@)",10,@"天地玄黄"]];
    NSLog(@"%s_callJSResult天地玄黄",__FUNCTION__);
}

/** 评测结果回调 @param errorCode 错误描述类 */
- (void)onError:(id)errorCode {
    NSLog(@"%s",__FUNCTION__);
}

/** 取消评测回调 */
- (void)onCancel {
    NSLog(@"%s",__FUNCTION__);
}

- (void)callJSWithFuntion:(NSString *)funtion {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.webView stringByEvaluatingJavaScriptFromString:funtion];
    });
}

- (void)dealloc {
    NSLog(@"%s",__FUNCTION__);
}


@end

